<template>
  <div class="app-container">
    <el-form :model="queryParams" ref="queryForm" :inline="true" v-show="showSearch" @submit.native.prevent>
      <el-form-item label="费用类型" prop="name">
        <el-input
          v-model="queryParams.name"
          placeholder="请输入费用类型名称"
          clearable
          size="small"
          @keyup.enter.native="handleQuery"
          maxlength="10"
          show-word-limit
        />
      </el-form-item>
      <el-form-item>
        <el-button type="primary" icon="el-icon-search" size="mini" @click="handleQuery">搜索</el-button>
        <el-button icon="el-icon-refresh" size="mini" @click="resetQuery">重置</el-button>
      </el-form-item>
    </el-form>

    <el-row :gutter="10" class="mb8" style="margin-bottom: 20px;">
      <el-col :span="1.5">
        <el-button
          type="primary"
          plain
          icon="el-icon-plus"
          size="mini"
          @click="handleAdd"
          v-hasPermi="['yongcanjiaofei:feiyongleixing:add']"
        >新增</el-button>
      </el-col>
    </el-row>

    <el-table v-loading="loading" :data="feiyongList">
      <el-table-column type="index" label="序号" width="55" align="center" />
      <el-table-column label="费用类型" align="center" prop="name" />
      <el-table-column label="收费标准" align="center">
        <template slot-scope="scope">
          ¥{{ scope.row.expenseMoney }}元/{{ scope.row.expenseUnits }}
        </template>
      </el-table-column>
      <el-table-column label="备注说明" align="center" prop="remark" :show-overflow-tooltip="true" />
      <el-table-column label="发布状态" align="center">
        <template slot-scope="scope">
          <el-tag :type="scope.row.status === '0' ? 'success' : 'info'">
            {{ scope.row.status === '0' ? '已启用' : '已停用' }}
          </el-tag>
        </template>
      </el-table-column>
      <el-table-column label="操作" align="center" class-name="small-padding fixed-width">
        <template slot-scope="scope">
          <el-button
            size="mini"
            type="text"
            icon="el-icon-edit"
            @click="handleUpdate(scope.row)"
            v-hasPermi="['yongcanjiaofei:feiyongleixing:edit']"
            v-if="scope.row.status == '1'"
          >修改</el-button>
          <el-button
            size="mini"
            type="text"
            icon="el-icon-delete"
            @click="handleDelete(scope.row)"
            v-if="scope.row.isDefault == '1' && scope.row.status == '1'"
            v-hasPermi="['yongcanjiaofei:feiyongleixing:remove']"
          >删除</el-button>
          <el-button
            size="mini"
            type="text"
            :class="scope.row.status === '0' ? 'error-btn' : 'success-btn'"
            @click="handleStatusChange(scope.row)"
            v-loading="scope.row.switchLoading"
          >{{ scope.row.status === '0' ? '停用' : '启用' }}</el-button>
        </template>
      </el-table-column>
    </el-table>
    
    <pagination
      v-show="total>0"
      :total="total"
      :page.sync="queryParams.pageNum"
      :limit.sync="queryParams.pageSize"
      @pagination="getList"
    />

    <!-- 添加或修改费用类型对话框 -->
    <el-dialog :title="title" :visible.sync="open" width="500px" append-to-body>
      <el-form ref="form" :model="form" :rules="rules" label-width="80px">
        <el-form-item label="费用类型" prop="name">
          <el-input v-model="form.name" placeholder="请输入费用类型名称" maxlength="10" show-word-limit clearable />
        </el-form-item>
        <el-form-item label="收费标准" prop="expenseMoney">
          <div class="expense-input">
            <span class="rmb-symbol">¥</span>
            <el-input-number 
              v-model="form.expenseMoney" 
              controls-position="right" 
              :min="0" 
              :precision="2"
              style="width: 60%;"
            />
            <el-select v-model="form.expenseUnits" placeholder="请选择单位" style="margin-left: 10px;width: 35%;">
              <el-option v-for="item in chargingUnitList" :key="item.dictValue" :label="item.dictLabel" :value="item.dictValue"></el-option>
            </el-select>
          </div>
        </el-form-item>
        <el-form-item label="备注说明" prop="remark">
          <el-input v-model="form.remark" type="textarea" placeholder="请输入备注说明" maxlength="200" show-word-limit clearable />
        </el-form-item>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button type="primary" @click="submitForm">发 布</el-button>
        <el-button @click="cancel">取 消</el-button>
      </div>
    </el-dialog>
  </div>
</template>

<script>
import { listFeiyongleixing, getFeiyongleixing, delFeiyongleixing, addFeiyongleixing, updateFeiyongleixing, changeFeiyongleixingStatus } from "@/api/yongcanjiaofei/feiyongleixing";
import { getDicts } from "@/api/system/dict/data";
export default {
  name: "",
  data() {
    return {
      // 遮罩层
      loading: true,
      // 显示搜索条件
      showSearch: true,
      // 总条数
      total: 0,
      // 费用类型表格数据
      feiyongList: [],
      // 弹出层标题
      title: "",
      // 是否显示弹出层
      open: false,
      // 查询参数
      queryParams: {
        pageNum: 1,
        pageSize: 10,
        name: undefined
      },
      // 表单参数
      form: {
        id: undefined,
        name: undefined,
        expenseMoney: 0,
        expenseUnits: '次',
        remark: undefined,
        status: "0"
      },
      // 表单校验
      rules: {
        name: [
          { required: true, message: "费用类型名称不能为空", trigger: "blur" }
        ],
        expenseMoney: [
          { required: true, message: "收费标准不能为空", trigger: "blur" }
        ],
        expenseUnits: [
          { required: true, message: "单位不能为空", trigger: "blur" }
        ]
      },
      chargingUnitList: [],
    };
  },
  created() {
    this.getList();
    this.getDicts();
  },
  methods: {
    getDicts() {
      getDicts('charging_unit').then(response => {
        console.log('字典',response);
        
        this.chargingUnitList = response.data;
      });
    },
    /** 查询费用类型列表 */
    getList() {
      this.loading = true;
      listFeiyongleixing(this.queryParams).then(response => {
        // 为每个费用类型添加临时状态和loading属性
        this.feiyongList = response.rows.map(item => {
          this.$set(item, 'switchLoading', false);
          this.$set(item, 'tempStatus', item.status);
          return item;
        });
        this.total = response.total;
        this.loading = false;
      });
    },
    // 取消按钮
    cancel() {
      this.open = false;
      this.reset();
    },
    // 表单重置
    reset() {
      this.form = {
        id: undefined,
        name: undefined,
        expenseMoney: 0,
        expenseUnits: '次',
        remark: undefined,
        status: "0"
      };
      this.resetForm("form");
    },
    /** 搜索按钮操作 */
    handleQuery() {
      this.queryParams.pageNum = 1;
      this.getList();
    },
    /** 重置按钮操作 */
    resetQuery() {
      this.resetForm("queryForm");
      this.handleQuery();
    },
    /** 新增按钮操作 */
    handleAdd() {
      this.reset();
      this.open = true;
      this.title = "新增费用类型";
    },
    /** 修改按钮操作 */
    handleUpdate(row) {
      this.reset();
      const id = row.id;
      getFeiyongleixing(id).then(response => {
        this.form = response.data;
        this.open = true;
        this.title = "修改费用类型";
      });
    },
    /** 提交按钮 */
    submitForm() {
      this.$refs["form"].validate(valid => {
        if (valid) {
          if (this.form.id != undefined) {
            updateFeiyongleixing(this.form).then(response => {
              this.msgSuccess("修改成功");
              this.open = false;
              this.getList();
            });
          } else {
            addFeiyongleixing(this.form).then(response => {
              this.msgSuccess("新增成功");
              this.open = false;
              this.getList();
            });
          }
        }
      });
    },
    /** 删除按钮操作 */
    handleDelete(row) {
      const ids = row.id;
      this.$confirm('删除后将在后续扫码用户的表单中生效，填写中的表不受影响,是否确认删除？').then(() => {
        return delFeiyongleixing(ids);
      }).then(() => {
        this.getList();
        this.msgSuccess("删除成功");
      }).catch(() => {});
    },
    /** 状态修改 */
    handleStatusChange(row) {
      if (row.switchLoading) return;
      
      // 还原状态，等待接口确认
      row.tempStatus = row.status;
      
      // 当前是启用状态，要进行停用操作
      if (row.status === '0') {
        this.$confirm('停用后将在后续扫码用户的表单中生效，填写中的表不受影响', '提示', {
          confirmButtonText: '确认',
          cancelButtonText: '取消',
          type: 'warning'
        }).then(() => {
          // 设置loading状态
          this.$set(row, 'switchLoading', true);
          return changeFeiyongleixingStatus(row.id, '1');
        }).then(() => {
          // 成功后改变状态
          row.status = '1';
          row.tempStatus = '1';
          this.msgSuccess("已停用");
        }).catch(err => {
          // 失败时保持原状态
          row.tempStatus = row.status;
        }).finally(() => {
          // 清除loading状态
          this.$set(row, 'switchLoading', false);
        });
      } else {
        // 当前是停用状态，要进行启用操作
        this.$confirm('启用后将在后续扫码用户的表单中生效，填写中的表将不会更新', '提示', {
          confirmButtonText: '确认',
          cancelButtonText: '取消',
          type: 'warning'
        }).then(() => {
          // 设置loading状态
          this.$set(row, 'switchLoading', true);
          return changeFeiyongleixingStatus(row.id, '0');
        }).then(() => {
          // 成功后改变状态
          row.status = '0';
          row.tempStatus = '0';
          this.msgSuccess("已启用");
        }).catch(err => {
          // 失败时保持原状态
          row.tempStatus = row.status;
          if (err !== 'cancel') {
            this.msgError('操作失败');
          }
        }).finally(() => {
          // 清除loading状态
          this.$set(row, 'switchLoading', false);
        });
      }
    }
  }
};
</script>

<style lang="scss" scoped>
.success-btn {
  color: #67C23A !important;
}

.error-btn {
  color: #F56C6C !important;
}

.expense-input {
  display: flex;
  align-items: center;
  position: relative;

  .rmb-symbol {
    margin-right: 5px;
    font-size: 14px;
    color: #606266;
    position: absolute;
    left: 6px;
    font-size: 16px;  
    z-index: 9;
  }
}

/* switch开关在loading时的样式 */
::v-deep .el-switch.is-disabled {
  opacity: 1;
  .el-switch__core {
    cursor: not-allowed;
    opacity: 0.8;
  }
}
</style> 